
import { GameInfo, GameRules } from '@/services/game/GameController';
import { ProForm, ProFormCheckbox, ProFormDateTimePicker, ProFormSelect, ProFormText, ProFormTextArea, ProFormUploadButton } from '@ant-design/pro-components';
import { Card, Flex, message, Modal, Upload, UploadFile, UploadProps } from 'antd';
import React from 'react';
import GameRulesFormTypeAView from './rules/GameRulesFormTypeAView';
import services from '@/services/game';

interface Props {
  gameId: string;
  modalVisible: boolean;
  onCancel: (show: boolean) => void;
  onReloadAndRest?: () => void;
}

const { queryGameRules, queryGameInfo, editGame } = services.GameController;

const handEditGame = async (values: GameInfo) => {
  const hide = message.loading('正在更新赛事');
  try {
    const { success, errorMessage } = await editGame(values);
    hide();
    if (success) {
      message.success('更新赛事成功');
      return true;
    } else {
      message.error(errorMessage);
      return false;
    }
  } catch (error) {
    hide();
    message.error('更新赛事请重试！');
    return false;
  }
}


const GameEditForm: React.FC<Props> = (props) => {
  const { gameId, modalVisible, onCancel, onReloadAndRest } = props;
  //赛事规则
  const [gameRules, setGameRules] = React.useState<GameRules>()
  const [fileList, setFileList] = React.useState<UploadFile[]>([]);
  const handleChange: UploadProps['onChange'] = ({ file, fileList: newFileList }) => {
    if (file.status === 'done') {
      newFileList.filter(item => item.uid === file.uid).map(item => {
        if (file.response?.success) {
          item.status = 'done'
          item.url = file.response?.data
        } else {
          item.status = 'error'
          item.error = '上传失败'
        }
      })
      if (file.response?.success == false) {
        message.error(`${file.name}上传失败`)
      }
    }
    setFileList(newFileList);
  }


  const onChangeType = (type: number) => {
    //赛制规则
    queryGameRules({ type: type }).then(res => {
      if (res.success) {
        setGameRules(res.data)
      }
    })
  }
  return (
    <Modal
      title="赛事编辑"
      open={modalVisible}
      onCancel={() => onCancel(false)}
      footer={null}
      width="1200px"
      height="100%"
      style={{ padding: 0, top: 10 }}
    >
      <ProForm<GameInfo>
        onFinish={async (values) => {
          var game = {
            ...values, ruleJson: JSON.stringify(values.ruleJson),
            url: fileList.filter(item => item.status === 'done').map(item => item.url)//宣传图图片
          } as GameInfo
          console.log(game);
          var success = await handEditGame(game)
          if (success) {
            onReloadAndRest?.()
          }
        }}
        request={async () => {
          const { success, data } = await queryGameInfo(gameId)
          if (success && data) {
            var list = Array<UploadFile>()
            data.url?.map(item =>
              list.push({
                uid: `01122`,
                name: `haibao`,
                status: 'done',
                url: item
              })
            )
            setFileList(list)

            if (data.type == 1) {
              //积分晋级赛规则
              setGameRules(JSON.parse(data.ruleJson))
            }

            return data
          } else {
            return {} as GameInfo
          }
        }}
      >
        <Card title='基础信息'>
          <ProFormUploadButton
            name="url"
            label="宣传海报"
            max={1}
            fileList={fileList}
            fieldProps={{
              name: 'file',
              listType: 'picture-card',
              accept: 'image/*',
              onChange: handleChange,
              beforeUpload: (file) => {
                const isLt10M = file.size / 1024 / 1024 < 10;
                if (!isLt10M) {
                  message.error('图片必须小于10MB');
                  return Upload.LIST_IGNORE;
                }
                return true;
              },
              onRemove: () => {
                setFileList([]);
                return true;
              }
            }}
            rules={[
              {
                required: true,
                validator: () =>
                  fileList.some(f => f.status === 'done')
                    ? Promise.resolve()
                    : Promise.reject('请上传有效的宣传海报')
              }
            ]}
            action="/pc/game/postFile"
            extra="(大小10m内)"
          />
          <ProFormText
            width="md"
            name="name"
            label="赛事名称"
            rules={[
              {
                required: true,
                message: '请输入赛事名称',
              },
            ]}
          />
          <ProFormText
            width="xl"
            name="address"
            label="详情地址"
            rules={[
              {
                required: true,
                message: '请输入详情地址',
              },
            ]}
          />
          <Flex style={{ justifyContent: 'space-between' }}>
            <ProFormText
              width="md"
              name="person"
              label="联系人"
              rules={[
                {
                  required: true,
                  message: '请输入联系人',
                },
              ]}
            />
            <ProFormText
              width="md"
              name="phone"
              label="联系电话"
              rules={[
                {
                  required: true,
                  message: '请输入联系电话',
                },
              ]}
            />
            <ProFormText
              width="md"
              name="allSize"
              label="比赛人数"
              rules={[
                {
                  pattern: /^[0-9]+$/,
                  required: true,
                  message: '请输入比赛人数',
                },
              ]}
            />
          </Flex>
          <Flex style={{ justifyContent: 'space-between' }}>
            <ProFormDateTimePicker
              width="md"
              name="offTime"
              label="报名截止时间"
              rules={[
                {
                  required: true,
                  message: '请选择报名截止时间',
                },
              ]}
            />
            <ProFormDateTimePicker
              width="md"
              name="startTime"
              label="开始时间"
              rules={[
                {
                  required: true,
                  message: '请选择比赛开始时间',
                },
              ]}
            />
            <ProFormDateTimePicker
              width="md"
              name="endTime"
              label="结束时间"
              rules={[
                {
                  required: true,
                  message: '请输入比赛结束时间',
                },
              ]}
            />
          </Flex>
          <Flex style={{ justifyContent: 'space-between' }}>
            <ProFormSelect
              width="md"
              name="range"
              label="公开范围"
              rules={[
                {
                  required: true,
                  message: '请选择公开范围',
                },
              ]}
              options={[
                {
                  value: 1,
                  label: '公开赛'
                }
              ]}
            />
            <ProFormSelect
              width="md"
              name="category"
              label="比赛类别"
              rules={[
                {
                  required: true,
                  message: '请选择比赛类别',
                },
              ]}
              options={[
                {
                  value: 1,
                  label: '双人赛'
                }
              ]}
            />
            <ProFormSelect
              width="md"
              name="type"
              label="赛制类型"
              rules={[
                {
                  required: true,
                  message: '请选择赛制类型',
                },
              ]}
              options={[
                {
                  value: 1,
                  label: '积分晋级赛'
                }
              ]}
              fieldProps={{
                onChange(value, option) {
                  onChangeType(value as number)
                },
              }}
            />
          </Flex>
          <Flex >

            <ProFormCheckbox
              layout='vertical'
              name="commRoules"
              fieldProps={{
                value: 1
              }}
            >
              是否使用通用规则
            </ProFormCheckbox>
            <ProFormCheckbox
              layout='vertical'
              name="singleOff"
              fieldProps={{
                value: 1
              }}
            >
              允许单人报名
            </ProFormCheckbox>
          </Flex>

        </Card>
        <Card title='赛制规则' style={{ marginTop: 10 }}>
          <ProForm.Item name='ruleJson'>
            {gameRules?.type == 1 && <GameRulesFormTypeAView name='ruleJson' data={JSON.parse(gameRules.json)} />}
          </ProForm.Item>
        </Card>
        <Card title='赛事介绍' style={{ marginTop: 10 }}>
          <ProFormTextArea
            name="introduce"
            placeholder="请输入赛事介绍"
          />
        </Card>

      </ProForm>
    </Modal>
  );
};

export default GameEditForm;
